# -*- coding: utf-8 -*-
import logging, traceback, os, json
from FooderRegist.manage import FoodRegist, FooderRegistError
from FooderUtil.redis_util import RedisUtil, FooderRedisError
from FooderUtil.table_util import TableUtil, FooderTableStoreError
from FooderUtil.oss_util import OSSUtil, FooderOSSError
from FooderUtil.authentication_tool import filter, FooderAuthenticationError
from FooderUtil.authentication_tool import FooderAuthenticationError
from FooderErrno import error_no

LOCAL = bool(os.getenv("local", ""))

def initializer(context):
    logger = logging.getLogger()
    logger.info('initializing')
    try:
        if LOCAL:
            redis_host = os.environ['REDIS_HOST_LOCAL']
            redis_password = os.environ['REDIS_PASSWORD']
            redis_port = os.environ['REDIS_PORT']
            oss_endpoint = os.environ['OSS_ENDPOINT_LOCAL']
            table_endpoint = os.environ['TABLE_ENDPOINT_LOCAL']
        else:
            redis_host = os.environ['REDIS_HOST']
            redis_password = os.environ['REDIS_PASSWORD']
            redis_port = os.environ['REDIS_PORT']
            oss_endpoint = os.environ['OSS_ENDPOINT']
            table_endpoint = os.environ['TABLE_ENDPOINT']
        bucket_name = os.environ['BUCKET_NAME']
        table_name = os.environ['TABLE_INSTANCE_NAME']
        global aesKey
        aesKey = os.environ['AES_KEY']
        global foodRedis
        foodRedis = RedisUtil(redis_host, redis_password, redis_port)
        global foodOss
        foodOss = OSSUtil(oss_endpoint, bucket_name, context)
        global foodTable
        foodTable = TableUtil(table_endpoint, table_name, context)
        global g_foodRegister
        g_foodRegister = FoodRegist()
    except Exception as e:
        logger.error(f'initializingError={traceback.format_exc()}')

def handler(event, context):
    logger = logging.getLogger()
    try:
        j_data, shopId = filter(event, aesKey, LOCAL, foodRedis)
        dishId = g_foodRegister.regist(j_data, context, shopId, foodRedis, foodTable, foodOss)
        data = {'dishId': dishId}
        return json.dumps(error_no.OK.data(data), ensure_ascii=False)
    except FooderAuthenticationError as e:
        logger.error(f'鉴权失败异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerToken.data(None), ensure_ascii=False)
    except FooderRedisError as e:
        logger.error(f'Redis异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerRuntime.data(None), ensure_ascii=False)
    except FooderRegistError as e:
        logger.error(f'菜品注册异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerRuntime.data(None), ensure_ascii=False)
    except FooderTableStoreError as e:
        logger.error(f'TableStore异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerRuntime.data(None), ensure_ascii=False)
    except FooderOSSError as e:
        logger.error(f'OSS异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerRuntime.data(None), ensure_ascii=False)
    except Exception as e:
        logger.error(f'服务运行的其它异常:{e.__dict__},traceback={traceback.format_exc()}')
        return json.dumps(error_no.ErrServerRuntime.data(None), ensure_ascii=False)